package com.zxp.common.core.validatecode.bean.image;

import cn.hutool.core.codec.Base64;
import com.zxp.common.core.validatecode.bean.ValidateCode;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * 图形验证码
 *
 * @author chentongwei@bshf360.com 2018-05-25 11:43
 */
@Data @NoArgsConstructor @AllArgsConstructor
public class ImageValidateCode extends ValidateCode {

    /** base64图形 */
    private String image;

    public ImageValidateCode(String code, int expireIn, String image) {
        super(code, expireIn);
        this.image = image;
    }

    public ImageValidateCode(BufferedImage image, String code, int expireIn) {
        super(code, expireIn);

        ByteArrayOutputStream byteArrayStream = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "JPEG", byteArrayStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //this.image = new sun.misc.BASE64Encoder().encodeBuffer(byteArrayStream.toByteArray());
        this.image = Base64.encode(byteArrayStream.toByteArray());
    }

}
